import 'package:flutter/material.dart';

class Course {
  final String id;
  final String title;
  final String description;
  final String imageUrl;
  final String instructor;
  final String instructorAvatar;
  final String category;
  final String level;
  final int duration; // 分钟
  final double price;
  final double rating;
  final int studentCount;
  final List<String> tags;
  final List<CourseChapter> chapters;
  final Map<String, dynamic> requirements;
  final Map<String, dynamic> outcomes;

  Course({
    required this.id,
    required this.title,
    required this.description,
    required this.imageUrl,
    required this.instructor,
    required this.instructorAvatar,
    required this.category,
    required this.level,
    required this.duration,
    required this.price,
    required this.rating,
    required this.studentCount,
    required this.tags,
    required this.chapters,
    required this.requirements,
    required this.outcomes,
  });

  Course copyWith({
    String? id,
    String? title,
    String? description,
    String? imageUrl,
    String? instructor,
    String? instructorAvatar,
    String? category,
    String? level,
    int? duration,
    double? price,
    double? rating,
    int? studentCount,
    List<String>? tags,
    List<CourseChapter>? chapters,
    Map<String, dynamic>? requirements,
    Map<String, dynamic>? outcomes,
  }) {
    return Course(
      id: id ?? this.id,
      title: title ?? this.title,
      description: description ?? this.description,
      imageUrl: imageUrl ?? this.imageUrl,
      instructor: instructor ?? this.instructor,
      instructorAvatar: instructorAvatar ?? this.instructorAvatar,
      category: category ?? this.category,
      level: level ?? this.level,
      duration: duration ?? this.duration,
      price: price ?? this.price,
      rating: rating ?? this.rating,
      studentCount: studentCount ?? this.studentCount,
      tags: tags ?? this.tags,
      chapters: chapters ?? this.chapters,
      requirements: requirements ?? this.requirements,
      outcomes: outcomes ?? this.outcomes,
    );
  }
}

class CourseChapter {
  final String id;
  final String title;
  final String description;
  final int duration; // 分钟
  final String videoUrl;
  final List<String> materials;
  final bool isCompleted;

  CourseChapter({
    required this.id,
    required this.title,
    required this.description,
    required this.duration,
    required this.videoUrl,
    required this.materials,
    this.isCompleted = false,
  });

  CourseChapter copyWith({
    String? id,
    String? title,
    String? description,
    int? duration,
    String? videoUrl,
    List<String>? materials,
    bool? isCompleted,
  }) {
    return CourseChapter(
      id: id ?? this.id,
      title: title ?? this.title,
      description: description ?? this.description,
      duration: duration ?? this.duration,
      videoUrl: videoUrl ?? this.videoUrl,
      materials: materials ?? this.materials,
      isCompleted: isCompleted ?? this.isCompleted,
    );
  }
}

class LearningPath {
  final String id;
  final String title;
  final String description;
  final String imageUrl;
  final String category;
  final String level;
  final List<String> courseIds;
  final int totalDuration;
  final Map<String, dynamic> skills;

  LearningPath({
    required this.id,
    required this.title,
    required this.description,
    required this.imageUrl,
    required this.category,
    required this.level,
    required this.courseIds,
    required this.totalDuration,
    required this.skills,
  });
}

class Instructor {
  final String id;
  final String name;
  final String avatar;
  final String bio;
  final String expertise;
  final double rating;
  final int studentCount;
  final List<String> achievements;
  final List<String> courseIds;

  Instructor({
    required this.id,
    required this.name,
    required this.avatar,
    required this.bio,
    required this.expertise,
    required this.rating,
    required this.studentCount,
    required this.achievements,
    required this.courseIds,
  });
}

class EducationProvider extends ChangeNotifier {
  List<Course> _courses = [];
  List<Course> _filteredCourses = [];
  List<LearningPath> _learningPaths = [];
  List<Instructor> _instructors = [];
  
  String _selectedCategory = 'all';
  String _selectedLevel = 'all';
  String _searchQuery = '';
  bool _isLoading = false;
  String? _error;
  
  // 用户学习数据
  List<String> _enrolledCourseIds = [];
  Map<String, Map<String, dynamic>> _courseProgress = {};
  Map<String, List<String>> _completedChapters = {};
  List<String> _favoriteCourseIds = [];
  Map<String, DateTime> _lastAccessTimes = {};
  Map<String, int> _studyTimeRecords = {}; // 课程ID -> 学习时长(分钟)

  // Getters
  List<Course> get courses => _courses;
  List<Course> get filteredCourses => _filteredCourses;
  List<LearningPath> get learningPaths => _learningPaths;
  List<Instructor> get instructors => _instructors;
  String get selectedCategory => _selectedCategory;
  String get selectedLevel => _selectedLevel;
  String get searchQuery => _searchQuery;
  bool get isLoading => _isLoading;
  String? get error => _error;
  List<String> get enrolledCourseIds => _enrolledCourseIds;
  Map<String, Map<String, dynamic>> get courseProgress => _courseProgress;
  Map<String, List<String>> get completedChapters => _completedChapters;
  List<String> get favoriteCourseIds => _favoriteCourseIds;
  Map<String, DateTime> get lastAccessTimes => _lastAccessTimes;
  Map<String, int> get studyTimeRecords => _studyTimeRecords;

  EducationProvider() {
    _loadInitialData();
  }

  void _loadInitialData() {
    _isLoading = true;
    notifyListeners();

    // 模拟加载数据
    Future.delayed(const Duration(milliseconds: 500), () {
      _courses = _generateMockCourses();
      _learningPaths = _generateMockLearningPaths();
      _instructors = _generateMockInstructors();
      _filteredCourses = List.from(_courses);
      _loadUserLearningData();
      _isLoading = false;
      notifyListeners();
    });
  }

  List<Course> _generateMockCourses() {
    return [
      Course(
        id: '1',
        title: '传统书法入门课程',
        description: '从基础笔画开始，学习楷书、行书的基本技法，了解书法的历史文化背景。适合零基础学员。',
        imageUrl: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=traditional%20chinese%20calligraphy%20learning%20class&image_size=landscape_4_3',
        instructor: '王老师',
        instructorAvatar: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=chinese%20calligraphy%20teacher%20portrait&image_size=square',
        category: 'calligraphy',
        level: 'beginner',
        duration: 480, // 8小时
        price: 299.0,
        rating: 4.8,
        studentCount: 1250,
        tags: ['书法', '楷书', '行书', '基础'],
        chapters: [
          CourseChapter(
            id: '1_1',
            title: '书法基础知识',
            description: '了解书法的历史、工具和基本概念',
            duration: 60,
            videoUrl: 'https://example.com/video1',
            materials: ['书法历史资料.pdf', '工具介绍.pdf'],
          ),
          CourseChapter(
            id: '1_2',
            title: '基本笔画练习',
            description: '学习横、竖、撇、捺等基本笔画',
            duration: 90,
            videoUrl: 'https://example.com/video2',
            materials: ['笔画练习册.pdf'],
          ),
          CourseChapter(
            id: '1_3',
            title: '楷书基础字形',
            description: '练习常用汉字的楷书写法',
            duration: 120,
            videoUrl: 'https://example.com/video3',
            materials: ['楷书字帖.pdf', '练习纸.pdf'],
          ),
          CourseChapter(
            id: '1_4',
            title: '行书入门',
            description: '学习行书的基本特点和写法',
            duration: 120,
            videoUrl: 'https://example.com/video4',
            materials: ['行书字帖.pdf'],
          ),
          CourseChapter(
            id: '1_5',
            title: '作品创作',
            description: '完成一幅完整的书法作品',
            duration: 90,
            videoUrl: 'https://example.com/video5',
            materials: ['创作指导.pdf', '作品纸.pdf'],
          ),
        ],
        requirements: {
          'tools': ['毛笔', '墨汁', '宣纸', '砚台'],
          'experience': '无需基础',
          'time': '每周2-3小时',
        },
        outcomes: {
          'skills': ['基本笔画掌握', '楷书书写', '行书入门', '作品创作'],
          'certificate': true,
        },
      ),
      Course(
        id: '2',
        title: '传统国画山水技法',
        description: '学习中国山水画的基本技法，包括构图、用笔、用墨、设色等核心技能。',
        imageUrl: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=traditional%20chinese%20landscape%20painting%20class&image_size=landscape_4_3',
        instructor: '李老师',
        instructorAvatar: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=chinese%20painting%20master%20portrait&image_size=square',
        category: 'painting',
        level: 'intermediate',
        duration: 720, // 12小时
        price: 599.0,
        rating: 4.9,
        studentCount: 890,
        tags: ['国画', '山水', '水墨', '技法'],
        chapters: [
          CourseChapter(
            id: '2_1',
            title: '山水画概论',
            description: '了解山水画的历史发展和基本理论',
            duration: 90,
            videoUrl: 'https://example.com/video6',
            materials: ['山水画史.pdf', '理论基础.pdf'],
          ),
          CourseChapter(
            id: '2_2',
            title: '笔墨技法',
            description: '学习各种笔法和墨法的运用',
            duration: 120,
            videoUrl: 'https://example.com/video7',
            materials: ['笔法示范.pdf', '墨法练习.pdf'],
          ),
          CourseChapter(
            id: '2_3',
            title: '山石画法',
            description: '掌握不同山石的画法和质感表现',
            duration: 150,
            videoUrl: 'https://example.com/video8',
            materials: ['山石技法.pdf', '参考图片.zip'],
          ),
          CourseChapter(
            id: '2_4',
            title: '树木云水',
            description: '学习树木、云彩、流水的表现技法',
            duration: 180,
            videoUrl: 'https://example.com/video9',
            materials: ['自然元素画法.pdf'],
          ),
          CourseChapter(
            id: '2_5',
            title: '构图与设色',
            description: '学习山水画的构图原理和设色技巧',
            duration: 120,
            videoUrl: 'https://example.com/video10',
            materials: ['构图法则.pdf', '色彩搭配.pdf'],
          ),
          CourseChapter(
            id: '2_6',
            title: '完整作品创作',
            description: '创作一幅完整的山水画作品',
            duration: 60,
            videoUrl: 'https://example.com/video11',
            materials: ['创作指导.pdf'],
          ),
        ],
        requirements: {
          'tools': ['毛笔', '国画颜料', '宣纸', '调色盘'],
          'experience': '有绘画基础更佳',
          'time': '每周4-5小时',
        },
        outcomes: {
          'skills': ['山水构图', '笔墨技法', '设色技巧', '作品创作'],
          'certificate': true,
        },
      ),
      Course(
        id: '3',
        title: '古琴演奏基础',
        description: '学习古琴的基本演奏技法，了解古琴文化，掌握经典曲目的演奏。',
        imageUrl: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=traditional%20chinese%20guqin%20music%20lesson&image_size=landscape_4_3',
        instructor: '张老师',
        instructorAvatar: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=chinese%20guqin%20master%20portrait&image_size=square',
        category: 'music',
        level: 'beginner',
        duration: 600, // 10小时
        price: 799.0,
        rating: 4.7,
        studentCount: 456,
        tags: ['古琴', '音乐', '传统', '演奏'],
        chapters: [
          CourseChapter(
            id: '3_1',
            title: '古琴文化与历史',
            description: '了解古琴的历史文化背景',
            duration: 60,
            videoUrl: 'https://example.com/video12',
            materials: ['古琴文化.pdf', '历史资料.pdf'],
          ),
          CourseChapter(
            id: '3_2',
            title: '古琴构造与调弦',
            description: '认识古琴的构造和调弦方法',
            duration: 90,
            videoUrl: 'https://example.com/video13',
            materials: ['古琴构造图.pdf', '调弦指南.pdf'],
          ),
          CourseChapter(
            id: '3_3',
            title: '基本指法练习',
            description: '学习古琴的基本指法技巧',
            duration: 150,
            videoUrl: 'https://example.com/video14',
            materials: ['指法图解.pdf', '练习曲谱.pdf'],
          ),
          CourseChapter(
            id: '3_4',
            title: '经典曲目学习',
            description: '学习《高山流水》等经典曲目',
            duration: 240,
            videoUrl: 'https://example.com/video15',
            materials: ['曲谱集.pdf', '演奏示范.mp3'],
          ),
          CourseChapter(
            id: '3_5',
            title: '演奏技巧提升',
            description: '提升演奏的表现力和技巧',
            duration: 60,
            videoUrl: 'https://example.com/video16',
            materials: ['技巧指导.pdf'],
          ),
        ],
        requirements: {
          'tools': ['古琴', '琴桌', '调音器'],
          'experience': '无需音乐基础',
          'time': '每周3-4小时',
        },
        outcomes: {
          'skills': ['基本指法', '曲目演奏', '音乐理解', '文化素养'],
          'certificate': true,
        },
      ),
      Course(
        id: '4',
        title: '传统茶艺文化',
        description: '学习中国传统茶艺，了解茶文化历史，掌握各种茶类的冲泡技巧。',
        imageUrl: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=traditional%20chinese%20tea%20ceremony%20class&image_size=landscape_4_3',
        instructor: '陈老师',
        instructorAvatar: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=chinese%20tea%20master%20portrait&image_size=square',
        category: 'culture',
        level: 'beginner',
        duration: 360, // 6小时
        price: 399.0,
        rating: 4.6,
        studentCount: 2100,
        tags: ['茶艺', '文化', '传统', '生活'],
        chapters: [
          CourseChapter(
            id: '4_1',
            title: '茶文化概述',
            description: '了解中国茶文化的历史和发展',
            duration: 60,
            videoUrl: 'https://example.com/video17',
            materials: ['茶文化史.pdf', '茶叶知识.pdf'],
          ),
          CourseChapter(
            id: '4_2',
            title: '茶具认识与使用',
            description: '认识各种茶具及其使用方法',
            duration: 90,
            videoUrl: 'https://example.com/video18',
            materials: ['茶具图鉴.pdf', '使用指南.pdf'],
          ),
          CourseChapter(
            id: '4_3',
            title: '绿茶冲泡技艺',
            description: '学习绿茶的冲泡方法和技巧',
            duration: 60,
            videoUrl: 'https://example.com/video19',
            materials: ['绿茶冲泡.pdf'],
          ),
          CourseChapter(
            id: '4_4',
            title: '乌龙茶与普洱茶',
            description: '掌握乌龙茶和普洱茶的冲泡要点',
            duration: 90,
            videoUrl: 'https://example.com/video20',
            materials: ['乌龙茶技法.pdf', '普洱茶知识.pdf'],
          ),
          CourseChapter(
            id: '4_5',
            title: '茶艺表演与礼仪',
            description: '学习茶艺表演的流程和礼仪',
            duration: 60,
            videoUrl: 'https://example.com/video21',
            materials: ['茶艺礼仪.pdf', '表演流程.pdf'],
          ),
        ],
        requirements: {
          'tools': ['茶具套装', '各类茶叶', '茶桌'],
          'experience': '无需基础',
          'time': '每周2小时',
        },
        outcomes: {
          'skills': ['茶艺技法', '文化理解', '礼仪修养', '生活品味'],
          'certificate': true,
        },
      ),
      Course(
        id: '5',
        title: '传统剪纸艺术',
        description: '学习中国传统剪纸技艺，从基础图案到复杂作品，传承民间艺术精髓。',
        imageUrl: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=traditional%20chinese%20paper%20cutting%20art%20class&image_size=landscape_4_3',
        instructor: '刘老师',
        instructorAvatar: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=chinese%20paper%20cutting%20artist%20portrait&image_size=square',
        category: 'craft',
        level: 'beginner',
        duration: 300, // 5小时
        price: 199.0,
        rating: 4.5,
        studentCount: 1680,
        tags: ['剪纸', '手工', '民间艺术', '创意'],
        chapters: [
          CourseChapter(
            id: '5_1',
            title: '剪纸艺术介绍',
            description: '了解剪纸的历史和文化意义',
            duration: 45,
            videoUrl: 'https://example.com/video22',
            materials: ['剪纸历史.pdf', '文化背景.pdf'],
          ),
          CourseChapter(
            id: '5_2',
            title: '工具与材料',
            description: '认识剪纸所需的工具和材料',
            duration: 30,
            videoUrl: 'https://example.com/video23',
            materials: ['工具介绍.pdf'],
          ),
          CourseChapter(
            id: '5_3',
            title: '基础图案练习',
            description: '学习简单的几何图案和花卉图案',
            duration: 90,
            videoUrl: 'https://example.com/video24',
            materials: ['基础图案.pdf', '练习模板.pdf'],
          ),
          CourseChapter(
            id: '5_4',
            title: '动物剪纸',
            description: '学习各种动物形象的剪纸技法',
            duration: 75,
            videoUrl: 'https://example.com/video25',
            materials: ['动物图案.pdf'],
          ),
          CourseChapter(
            id: '5_5',
            title: '创意作品设计',
            description: '设计并制作个人创意剪纸作品',
            duration: 60,
            videoUrl: 'https://example.com/video26',
            materials: ['设计指导.pdf', '创意模板.pdf'],
          ),
        ],
        requirements: {
          'tools': ['剪刀', '刻刀', '彩纸', '垫板'],
          'experience': '无需基础',
          'time': '每周1-2小时',
        },
        outcomes: {
          'skills': ['剪纸技法', '图案设计', '创意思维', '手工技能'],
          'certificate': true,
        },
      ),
    ];
  }

  List<LearningPath> _generateMockLearningPaths() {
    return [
      LearningPath(
        id: 'path_1',
        title: '传统文化艺术大师之路',
        description: '从书法、绘画到音乐，全面掌握中华传统艺术精髓',
        imageUrl: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=traditional%20chinese%20arts%20learning%20path&image_size=landscape_4_3',
        category: 'comprehensive',
        level: 'beginner',
        courseIds: ['1', '2', '3'],
        totalDuration: 1800, // 30小时
        skills: {
          'primary': ['书法', '国画', '古琴'],
          'secondary': ['文化理解', '艺术鉴赏', '创作能力'],
        },
      ),
      LearningPath(
        id: 'path_2',
        title: '生活美学修养课程',
        description: '通过茶艺、剪纸等传统技艺，提升生活品味和文化修养',
        imageUrl: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=traditional%20lifestyle%20aesthetics%20learning&image_size=landscape_4_3',
        category: 'lifestyle',
        level: 'beginner',
        courseIds: ['4', '5'],
        totalDuration: 660, // 11小时
        skills: {
          'primary': ['茶艺', '剪纸'],
          'secondary': ['生活美学', '文化素养', '手工技能'],
        },
      ),
    ];
  }

  List<Instructor> _generateMockInstructors() {
    return [
      Instructor(
        id: 'instructor_1',
        name: '王老师',
        avatar: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=chinese%20calligraphy%20teacher%20portrait&image_size=square',
        bio: '中国书法家协会会员，从事书法教学20余年，擅长楷书、行书教学。',
        expertise: '书法教学',
        rating: 4.8,
        studentCount: 3200,
        achievements: ['中国书法家协会会员', '省级书法比赛一等奖', '优秀教师奖'],
        courseIds: ['1'],
      ),
      Instructor(
        id: 'instructor_2',
        name: '李老师',
        avatar: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=chinese%20painting%20master%20portrait&image_size=square',
        bio: '国画大师，专攻山水画30年，作品多次在国内外展出。',
        expertise: '国画山水',
        rating: 4.9,
        studentCount: 2100,
        achievements: ['国家一级美术师', '国际艺术展金奖', '文化传承贡献奖'],
        courseIds: ['2'],
      ),
      Instructor(
        id: 'instructor_3',
        name: '张老师',
        avatar: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=chinese%20guqin%20master%20portrait&image_size=square',
        bio: '古琴演奏家，师承名门，致力于古琴文化的传承与推广。',
        expertise: '古琴演奏',
        rating: 4.7,
        studentCount: 890,
        achievements: ['古琴协会理事', '传统音乐传承人', '文化艺术奖'],
        courseIds: ['3'],
      ),
      Instructor(
        id: 'instructor_4',
        name: '陈老师',
        avatar: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=chinese%20tea%20master%20portrait&image_size=square',
        bio: '茶艺大师，国家高级茶艺师，专注茶文化研究与教学15年。',
        expertise: '茶艺文化',
        rating: 4.6,
        studentCount: 4500,
        achievements: ['国家高级茶艺师', '茶文化研究专家', '优秀传承人'],
        courseIds: ['4'],
      ),
      Instructor(
        id: 'instructor_5',
        name: '刘老师',
        avatar: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=chinese%20paper%20cutting%20artist%20portrait&image_size=square',
        bio: '民间艺术家，剪纸技艺传承人，作品被多家博物馆收藏。',
        expertise: '剪纸艺术',
        rating: 4.5,
        studentCount: 2800,
        achievements: ['非遗传承人', '民间艺术大师', '文化保护贡献奖'],
        courseIds: ['5'],
      ),
    ];
  }

  void _loadUserLearningData() {
    // 模拟加载用户学习数据
    _enrolledCourseIds = ['1', '4'];
    _favoriteCourseIds = ['2', '3', '5'];
    
    _courseProgress = {
      '1': {
        'progress': 0.6, // 60%完成
        'enrollDate': DateTime.now().subtract(const Duration(days: 15)),
        'lastAccess': DateTime.now().subtract(const Duration(days: 1)),
      },
      '4': {
        'progress': 0.3, // 30%完成
        'enrollDate': DateTime.now().subtract(const Duration(days: 5)),
        'lastAccess': DateTime.now().subtract(const Duration(hours: 2)),
      },
    };
    
    _completedChapters = {
      '1': ['1_1', '1_2', '1_3'], // 完成了前3章
      '4': ['4_1', '4_2'], // 完成了前2章
    };
    
    _lastAccessTimes = {
      '1': DateTime.now().subtract(const Duration(days: 1)),
      '4': DateTime.now().subtract(const Duration(hours: 2)),
    };
    
    _studyTimeRecords = {
      '1': 240, // 4小时
      '4': 90,  // 1.5小时
    };
  }

  // 搜索和筛选
  void setSearchQuery(String query) {
    _searchQuery = query;
    _applyFilters();
  }

  void setCategory(String category) {
    _selectedCategory = category;
    _applyFilters();
  }

  void setLevel(String level) {
    _selectedLevel = level;
    _applyFilters();
  }

  void _applyFilters() {
    _filteredCourses = _courses.where((course) {
      final matchesCategory = _selectedCategory == 'all' || course.category == _selectedCategory;
      final matchesLevel = _selectedLevel == 'all' || course.level == _selectedLevel;
      final matchesSearch = _searchQuery.isEmpty ||
          course.title.toLowerCase().contains(_searchQuery.toLowerCase()) ||
          course.description.toLowerCase().contains(_searchQuery.toLowerCase()) ||
          course.tags.any((tag) => tag.toLowerCase().contains(_searchQuery.toLowerCase()));
      return matchesCategory && matchesLevel && matchesSearch;
    }).toList();
    notifyListeners();
  }

  // 课程操作
  Future<bool> enrollCourse(String courseId) async {
    try {
      _isLoading = true;
      notifyListeners();

      // 模拟网络请求
      await Future.delayed(const Duration(seconds: 1));

      if (!_enrolledCourseIds.contains(courseId)) {
        _enrolledCourseIds.add(courseId);
        _courseProgress[courseId] = {
          'progress': 0.0,
          'enrollDate': DateTime.now(),
          'lastAccess': DateTime.now(),
        };
        _completedChapters[courseId] = [];
        _lastAccessTimes[courseId] = DateTime.now();
        _studyTimeRecords[courseId] = 0;
      }
      
      _isLoading = false;
      notifyListeners();
      return true;
    } catch (e) {
      _error = '报名失败: $e';
      _isLoading = false;
      notifyListeners();
      return false;
    }
  }

  Future<bool> unenrollCourse(String courseId) async {
    try {
      _isLoading = true;
      notifyListeners();

      // 模拟网络请求
      await Future.delayed(const Duration(seconds: 1));

      _enrolledCourseIds.remove(courseId);
      _courseProgress.remove(courseId);
      _completedChapters.remove(courseId);
      _lastAccessTimes.remove(courseId);
      _studyTimeRecords.remove(courseId);
      
      _isLoading = false;
      notifyListeners();
      return true;
    } catch (e) {
      _error = '退课失败: $e';
      _isLoading = false;
      notifyListeners();
      return false;
    }
  }

  Future<bool> completeChapter(String courseId, String chapterId) async {
    try {
      if (!_enrolledCourseIds.contains(courseId)) {
        return false;
      }

      final completedList = _completedChapters[courseId] ?? [];
      if (!completedList.contains(chapterId)) {
        completedList.add(chapterId);
        _completedChapters[courseId] = completedList;
        
        // 更新课程进度
        final course = getCourseById(courseId);
        if (course != null) {
          final progress = completedList.length / course.chapters.length;
          _courseProgress[courseId]?['progress'] = progress;
        }
        
        // 更新最后访问时间
        _lastAccessTimes[courseId] = DateTime.now();
        
        notifyListeners();
      }
      
      return true;
    } catch (e) {
      _error = '更新进度失败: $e';
      notifyListeners();
      return false;
    }
  }

  void recordStudyTime(String courseId, int minutes) {
    if (_enrolledCourseIds.contains(courseId)) {
      _studyTimeRecords[courseId] = (_studyTimeRecords[courseId] ?? 0) + minutes;
      _lastAccessTimes[courseId] = DateTime.now();
      notifyListeners();
    }
  }

  void toggleFavorite(String courseId) {
    if (_favoriteCourseIds.contains(courseId)) {
      _favoriteCourseIds.remove(courseId);
    } else {
      _favoriteCourseIds.add(courseId);
    }
    notifyListeners();
  }

  // 查询方法
  Course? getCourseById(String id) {
    try {
      return _courses.firstWhere((course) => course.id == id);
    } catch (e) {
      return null;
    }
  }

  Instructor? getInstructorById(String id) {
    try {
      return _instructors.firstWhere((instructor) => instructor.id == id);
    } catch (e) {
      return null;
    }
  }

  LearningPath? getLearningPathById(String id) {
    try {
      return _learningPaths.firstWhere((path) => path.id == id);
    } catch (e) {
      return null;
    }
  }

  bool isEnrolled(String courseId) {
    return _enrolledCourseIds.contains(courseId);
  }

  bool isFavorite(String courseId) {
    return _favoriteCourseIds.contains(courseId);
  }

  bool isChapterCompleted(String courseId, String chapterId) {
    return _completedChapters[courseId]?.contains(chapterId) ?? false;
  }

  double getCourseProgress(String courseId) {
    return _courseProgress[courseId]?['progress'] ?? 0.0;
  }

  int getStudyTime(String courseId) {
    return _studyTimeRecords[courseId] ?? 0;
  }

  DateTime? getLastAccessTime(String courseId) {
    return _lastAccessTimes[courseId];
  }

  // 获取推荐课程
  List<Course> getRecommendedCourses({int limit = 5}) {
    final recommended = <Course>[];
    
    // 基于用户收藏和已报名课程推荐
    final userCategories = <String>{};
    for (final courseId in [..._enrolledCourseIds, ..._favoriteCourseIds]) {
      final course = getCourseById(courseId);
      if (course != null) {
        userCategories.add(course.category);
      }
    }
    
    // 推荐相同类别的课程
    for (final course in _courses) {
      if (!_enrolledCourseIds.contains(course.id) && 
          userCategories.contains(course.category)) {
        recommended.add(course);
      }
    }
    
    // 如果推荐不够，添加热门课程
    if (recommended.length < limit) {
      final popularCourses = _courses
          .where((course) => !recommended.contains(course) && !_enrolledCourseIds.contains(course.id))
          .toList()
        ..sort((a, b) => b.studentCount.compareTo(a.studentCount));
      
      recommended.addAll(popularCourses.take(limit - recommended.length));
    }
    
    return recommended.take(limit).toList();
  }

  // 获取正在学习的课程
  List<Course> getEnrolledCourses() {
    return _enrolledCourseIds
        .map((id) => getCourseById(id))
        .where((course) => course != null)
        .cast<Course>()
        .toList();
  }

  // 获取收藏的课程
  List<Course> getFavoriteCourses() {
    return _favoriteCourseIds
        .map((id) => getCourseById(id))
        .where((course) => course != null)
        .cast<Course>()
        .toList();
  }

  // 获取课程分类
  List<String> getCategories() {
    final categories = _courses.map((c) => c.category).toSet().toList();
    categories.sort();
    return ['all', ...categories];
  }

  // 获取课程级别
  List<String> getLevels() {
    final levels = _courses.map((c) => c.level).toSet().toList();
    levels.sort();
    return ['all', ...levels];
  }

  // 获取用户学习统计
  Map<String, dynamic> getUserLearningStats() {
    final totalStudyTime = _studyTimeRecords.values.fold(0, (sum, time) => sum + time);
    final totalProgress = _courseProgress.values
        .map((data) => data['progress'] as double)
        .fold(0.0, (sum, progress) => sum + progress);
    final averageProgress = _courseProgress.isNotEmpty ? totalProgress / _courseProgress.length : 0.0;
    
    final completedCourses = _courseProgress.values
        .where((data) => (data['progress'] as double) >= 1.0)
        .length;
    
    return {
      'enrolledCourses': _enrolledCourseIds.length,
      'completedCourses': completedCourses,
      'favoriteCourses': _favoriteCourseIds.length,
      'totalStudyTime': totalStudyTime, // 分钟
      'averageProgress': averageProgress,
      'totalChaptersCompleted': _completedChapters.values
          .map((chapters) => chapters.length)
          .fold(0, (sum, count) => sum + count),
    };
  }

  // 刷新数据
  Future<void> refresh() async {
    _error = null;
    _loadInitialData();
  }

  // 清除错误
  void clearError() {
    _error = null;
    notifyListeners();
  }
}